package com.zbj.data.jpa.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.google.common.collect.Maps;
import com.zbj.data.jpa.datasource.DBType;
import com.zbj.data.jpa.datasource.DynamicDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

import javax.sql.DataSource;
import java.util.Map;

/**
 * JPADataSourceConfig
 * http://www.jianshu.com/p/34730e595a8c
 * @author weigang
 * @create 2017-09-10
 **/
@Configuration
@EnableJpaAuditing
public class JPADataSourceConfig {

	@Bean(name = DBType.MASTER, initMethod = "init", destroyMethod = "close")
	@Primary
	@ConfigurationProperties(prefix = "spring.datasource.druid.master")
	public DataSource masterDruidDataSource(){
		return new DruidDataSource();
	}

	@Bean(name = DBType.SLAVE, initMethod = "init", destroyMethod = "close")
	@ConfigurationProperties(prefix = "spring.datasource.druid.slave")
	public DataSource slaveDruidDataSource(){
		return new DruidDataSource();
	}

	/**
	 * 注入AbstractRoutingDataSource
	 * @param masterDataSource
	 * @param slaveDataSource
	 * @return
	 * @throws Exception
	 */
	@Bean
	public DynamicDataSource dynamicDataSource(@Qualifier(DBType.MASTER) DataSource masterDataSource,
											   @Qualifier(DBType.SLAVE) DataSource slaveDataSource){

		DynamicDataSource dynamicDataSource = new DynamicDataSource();
		Map<Object, Object> targetDataSource = Maps.newHashMap();
		targetDataSource.put(DBType.MASTER, masterDataSource);
		targetDataSource.put(DBType.SLAVE, slaveDataSource);
		dynamicDataSource.setTargetDataSources(targetDataSource);
		dynamicDataSource.setDefaultTargetDataSource(masterDataSource);

		return dynamicDataSource;
	}

}
